<?php
/**
 * Database model, 'user' table.
 * 
 * @author james
 *
 */
class User extends Zend_Db_Table_Abstract {
	
	protected $_primary = 'id';
	protected $_name = 'user';
	
	/**
	 * Find active user by email and password.
	 * 
	 * @param $email
	 * @param $password
	 * @return search result
	 */
	public function findActiveByEmailAndPassword($email, $password) {
		$where = $this->select()->where("upper(openid)=upper(?)", $email)
		->where("upper(password)=upper(?)", $password)
		->where("open_id_provider=?", OpenIdProvider::TRASSOL);
		return $this->fetchRow($where);
	}
	
	/**
	 * Add user to database if it's new.
	 * 
	 * @param $idProvider
	 * @param $data
	 * @return return added new user
	 */
	public function addUser($idProvider, $data) {
		$user = null;
		if ($idProvider == OpenIdProvider::TRASSOL) {
			$user = $this->findActiveByEmailAndPassword($data["openid"], $data["password"]);
			if (!isset($user)) {
				$user = new User();
				$data["open_id_provider"] = $idProvider;
				$user->insert($data);
			}
		}
		return $user;
	}
	
/**
     * Find pending user by given key and email.
     * 
     * @param $key
     * @param $email
     * @return return found user
     */
    public function findUserByKeyAndEmail($key, $email) {
        $where = $this->select()->where("registration_key=?", $key)
        ->where("openid=?", $email)
        ->where("open_id_provider=?", OpenIdProvider::TRASSOL);
        return $this->fetchRow($where);
    }
    
    /**
     * Update user status.
     * 
     * @param $id user id
     * @param $status status to be updated
     */
    public function updateUserStatus($id, $status) {
        $user = $this->find($id)->current();
        $user->status = $status;
        $user->save();
        
    }
}
?>